package com.sky.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 新增菜品
     * @param dishDTO
     */
    @Transactional
    public void addDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //向菜品表插入一条数据
        dishMapper.insert(dish);
        //主键回显
        Long dishId = dish.getId();
        //判断是否有口味
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        if (flavorList != null && flavorList.size() > 0){
            //有，向口味表插入N条
            flavorList.stream().forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatchDishFlavor(flavorList);
        }

        //清理分类id下的缓存
        log.info("清理{}下的缓存",dishDTO.getCategoryId());
       redisTemplate.delete("dish:" + dishDTO.getCategoryId());
    }


    /**
     * 菜品分页条件查询
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult dishPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.dishPage(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page);
    }


    /**
     * 根据id查询菜品和菜品口味
     * @param id
     * @return
     */
    public DishVO getDishWithFlavorById(Long id) {
        //查菜品
        Dish dish = dishMapper.getDishById(id);
        //查口味
        List<DishFlavor> flavorList = dishFlavorMapper.getDishFlavorByDishId(id);
        //封装DishVo
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavorList);
        return dishVO;
    }

    /**
     * 根据id批量删除菜品
     * @param ids
     */
    @Transactional
    public void deleteBatchDishById(List<Long> ids) {
        int count = dishMapper.getDishesOnSale(ids);
        if (count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        count = setmealDishMapper.getSetmealsOnSale(ids);
        if (count > 0 ){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品
        dishMapper.deleteBatchDishById(ids);
        //删除口味
        dishFlavorMapper.deleteBatchDishFlavor(ids);

        //清理所有缓存
        log.info("清理所有缓存");
        Set<String> keys = redisTemplate.keys("dish:*");
        redisTemplate.delete(keys);
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Transactional
    public void updateDishById(DishDTO dishDTO) {
        //修改菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDishById(dish);

        //删除口味表中数据
        dishFlavorMapper.deleteBatchDishFlavor(Collections.singletonList(dishDTO.getId()));
        //向口味表插入N条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.stream().forEach(dishFlavor -> {
            dishFlavor.setDishId(dishDTO.getId());
        });
        dishFlavorMapper.insertBatchDishFlavor(flavors);

        //清理当前分类id下的缓存
        log.info("清理{}下的缓存",dishDTO.getCategoryId());
        redisTemplate.delete("dish:" + dishDTO.getCategoryId());
    }

    /**
     * 起售停售菜品
     * @param status
     * @param id
     */
    public void updateDishStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status).build();
        dishMapper.updateDishById(dish);
        //清理所有缓存
        log.info("清理所有缓存");
        Set<String> keys = redisTemplate.keys("dish:*");
        redisTemplate.delete(keys);
    }

    /**
     * 根据分类id查菜品
     * @param categoryId
     * @return
     */
    public List<Dish> getDishesByCategoryId(Long categoryId) {
        return dishMapper.getDishesByCategoryId(categoryId);
    }


    /**
     * 根据分类id查询菜品及口味
     * @param dish
     * @return
     */
    public List<DishVO> getDishesWithflavor(Dish dish) {
        String jsonArrayStr = redisTemplate.opsForValue().get("dish:" + dish.getCategoryId());
        log.info("缓存的菜品数据为： {}",jsonArrayStr);
        if (!StrUtil.isBlank(jsonArrayStr)){
            JSONArray jsonArray = JSONUtil.parseArray(jsonArrayStr);
            List<DishVO> dishVOList = JSONUtil.toList(jsonArray, DishVO.class);
            return dishVOList;
        }
        List<DishVO> dishVOList = dishMapper.getDishesWithflavor(dish);

        String jsonStr = JSONUtil.toJsonStr(dishVOList);
        redisTemplate.opsForValue().set("dish:" + dish.getCategoryId(),jsonStr);
        return dishVOList;
    }
}
